import axios from 'axios'
import { Session } from '/@/utils/storage'

// 创建专用的axios实例
const apiService = axios.create({
	baseURL: 'http://api.erp.byesame.com/jeecg-boot',
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' }
})

// 请求拦截器
apiService.interceptors.request.use(
	(config) => {
		const token = Session.get('token')
		console.log('请求拦截器中的token:', token)
		console.log('token类型:', typeof token)
		console.log('token长度:', token ? token.length : 0)
		
		if (token) {
			// 尝试多种认证头部格式
			config.headers['Authorization'] = `Bearer ${token}`
			config.headers['X-Access-Token'] = token
			console.log('设置的Authorization头:', config.headers['Authorization'])
			console.log('设置的X-Access-Token头:', config.headers['X-Access-Token'])
		} else {
			console.log('没有找到token')
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
apiService.interceptors.response.use(
	(response) => {
		const res = response.data
		
		// 成功逻辑：code 为 200 或 0 时通过
		if (res.code === 200 || res.code === 0) {
			return res
		}
		
		// 失败逻辑：code 不是 200/0 时拦截
		if (res.code === 401 || res.code === 4001) {
			Session.clear()
			window.location.href = '/'
			throw new Error('Token失效，请重新登录!')
		} else {
			throw new Error(res.message || '请求失败')
		}
	},
	(error) => {
		console.error('API请求失败:', error)
		throw error
	}
)

// 通用请求方法
const request = async (url, params = {}) => {
	try {
		const response = await apiService.get(url, { params })
		return response
	} catch (error) {
		console.error('API请求失败:', error)
		throw error
	}
}

// 销售发票相关API
export const salesInvoiceAPI = {
	// 获取销售发票列表
	getList: (params) => {
		const requestParams = {
			t: Date.now(),
			isVoided: 0,
			column: 'createTime',
			order: 'desc',
			field: 'id,,,billNo,billDate,subject,customerId_dictText,invoiceType_dictText,invoiceNo,invoiceDate,amt,billStage_dictText,isEffective_dictText,isClosed_dictText,isVoided_dictText,isAuto_dictText,isRubric_dictText,remark,effectiveTime,approver_dictText,createTime,createBy_dictText,sysOrgCode_dictText,updateTime,updateBy_dictText,action',
			pageNo: params.pageNo || 1,
			pageSize: params.pageSize || 10,
			...params
		}
		
		return request('/finance/finSalInvoice/list/0/0', requestParams)
	}
} 